﻿var pageIdField = "data-pageId";
var backuptitle=document.title;

function domainTest() {
    return true;
}

function setUrl(url) {
    
}

function __refreshMenu(menuKey) {

    WebUIJS.SetActiveMenuKey(menuKey);
}

function __systemMessageHandler(source,funcName, args,callbackArgs) {
    switch (funcName) {
        case "SetMenuKey":
            {
                WebUIJS.SetActiveMenuKey(args.MenuKey);
                return true;
            }
        case "SetUrl":
        {
            setUrl(args.Url);

            return true;
        }
        case "Resize":
            resizeCrossDomainIframe(args);
            return true;
        case "SetTitle":
            setTitle(args,source);
            return true;
        default:
            return false;
    }
}


function resizeCrossDomainIframe(args) {
    var argHeight = args.Height;

    if ($(window).height()-32 > argHeight) {
        argHeight = $(window).height()-32;
    }

    if (argHeight<800) {
        argHeight = 800;
    }

    $("#content").attr("height", argHeight + 32 + "px");
    //$("#content").attr("width", args.Width + "px");
}

function setTitle(args,source) {
    window.title = args.Title;
    document.title = args.Title;

    if(source && source!=null){
        $("#content-wrapper .content-iframe .tab-pane").each(function(){
            var pane=$(this);

            var iframe=$(pane).find("iframe");

            if(iframe.length<=0){
                return;
            }

            if(iframe[0].contentWindow==source){
                var pageid=pane.data("pageid");

                WebUIJS_Frame.editTabTitle(pageid,args.Title);
            }
        })
    }


}

var WebUIJS_Frame = {
    updateIFrameHeight:function(height){
        $(".tab_iframe").css({
            height: height,
            width: "100%"
        });

    },

    //初始化iframe内容页高度
    handleIframeContent: function() {
        var ht = $(window).height(); //获取浏览器窗口的整体高度；

        var $footer = $(".main-footer");
        var $header = $(".main-header");
        var $tabs = $(".content-tabs");

        var height = WebUIJS_Frame.getViewPort().height - $footer.outerHeight() - $header.outerHeight();
        if ($tabs.is(":visible")) {
            height = height - $tabs.outerHeight();
        }

        $(".tab_iframe").css({
            height: height,
            width: "100%"
        });

        //var width = App.getViewPort().width- $(".page-sidebar-menu").width();
        /*$(".tab_iframe").css({
         });*/
    },

    getViewPort: function() {
        var e = window,
            a = 'inner';
        if (!('innerWidth' in window)) {
            a = 'client';
            e = document.documentElement || document.body;
        }

        return {
            width: e[a + 'Width'],
            height: e[a + 'Height']
        };
    },

    getPageId: function(element) {
        if (element instanceof jQuery) {
            return element.attr(pageIdField);
        } else {
            return $(element).attr(pageIdField);
        }
    },

    findTabTitle: function(pageId) {
        var $ele = null;
        $(".page-tabs-content").find("a.menu_tab").each(function() {
            var $a = $(this);
            if ($a.attr(pageIdField) == pageId) {
                $ele = $a;
                return false; //退出循环
            }
        });
        return $ele;
    },

    findTabPanel: function(pageId) {
        var $ele = null;
        $("#tab-content").find("div.tab-pane").each(function() {
            var $div = $(this);
            if ($div.attr(pageIdField) == pageId) {
                $ele = $div;
                return false; //退出循环
            }
        });
        return $ele;
    },

    findIframeById: function(pageId) {
        return WebUIJS_Frame.findTabPanel(pageId).children("iframe");
    },

    fixIframeCotent: function() {
        setTimeout(function() {
                //_runResizeHandlers();
                WebUIJS_Frame.handleIframeContent();
            },
            50);
    },

    getActivePageId: function() {
        var $a = $('.page-tabs-content').find('.active');
        return WebUIJS_Frame.getPageId($a);
    },

    canRemoveTab: function(pageId) {
        return WebUIJS_Frame.findTabTitle(pageId).find('.fa-remove').length > 0;
    },

    //激活Tab,通过id
    activeTabByPageId: function(pageId) {
        $(".menu_tab").removeClass("active");
        $("#tab-content").find(".active").removeClass("active");
        //激活TAB

        var tab=WebUIJS_Frame.findTabTitle(pageId);

        if(tab && tab.length>0){
            var $title = tab.addClass('active');
            WebUIJS_Frame.findTabPanel(pageId).addClass("active");
            // scrollToTab($('.menu_tab.active'));
            WebUIJS_Frame.scrollToTab($title[0]);

            
    
            if($title && $title!=null){
                WebUIJS.SetActiveMenuKey($title.data("menukey"));
                setTitle({Title:$title.text()});
            }
            else{
                setTitle({Title:backuptitle} );
            }
        }
        else{
            setTitle({Title:backuptitle} );
        }
        
    },

    //滚动条滚动到左边
    scrollTabLeft :function () {
        var marginLeftVal = Math.abs(parseInt($('.page-tabs-content').css('margin-left')));
        var tabOuterWidth = WebUIJS_Frame.calSumWidth($(".content-tabs").children().not(".menuTabs"));
        var visibleWidth = $(".content-tabs").outerWidth(true) - tabOuterWidth;
        var scrollVal = 0;
        if ($(".page-tabs-content").width() < visibleWidth) {
            return false;
        } else {
            var tabElement = $(".menu_tab:first");
            var offsetVal = 0;
            while ((offsetVal + $(tabElement).outerWidth(true)) <= marginLeftVal) {
                offsetVal += $(tabElement).outerWidth(true);
                tabElement = $(tabElement).next();
            }
            offsetVal = 0;
            if (WebUIJS_Frame.calSumWidth($(tabElement).prevAll()) > visibleWidth) {
                while ((offsetVal + $(tabElement).outerWidth(true)) < (visibleWidth) && tabElement.length > 0) {
                    offsetVal += $(tabElement).outerWidth(true);
                    tabElement = $(tabElement).prev();
                }
                scrollVal = WebUIJS_Frame.calSumWidth($(tabElement).prevAll());
            }
        }
        $('.page-tabs-content').animate({
            marginLeft: 0 - scrollVal + 'px'
        }, "fast");
    },

    //滚动条滚动到右边
    scrollTabRight : function () {
        var marginLeftVal = Math.abs(parseInt($('.page-tabs-content').css('margin-left')));
        var tabOuterWidth = WebUIJS_Frame.calSumWidth($(".content-tabs").children().not(".menuTabs"));
        var visibleWidth = $(".content-tabs").outerWidth(true) - tabOuterWidth;
        var scrollVal = 0;
        if ($(".page-tabs-content").width() < visibleWidth) {
            return false;
        } else {
            var tabElement = $(".menu_tab:first");
            var offsetVal = 0;
            while ((offsetVal + $(tabElement).outerWidth(true)) <= marginLeftVal) {
                offsetVal += $(tabElement).outerWidth(true);
                tabElement = $(tabElement).next();
            }
            offsetVal = 0;
            while ((offsetVal + $(tabElement).outerWidth(true)) < (visibleWidth) && tabElement.length > 0) {
                offsetVal += $(tabElement).outerWidth(true);
                tabElement = $(tabElement).next();
            }
            scrollVal = WebUIJS_Frame.calSumWidth($(tabElement).prevAll());
            if (scrollVal > 0) {
                $('.page-tabs-content').animate({
                    marginLeft: 0 - scrollVal + 'px'
                }, "fast");
            }
        }
    },

    scrollToTab: function(element) {
        //element是tab(a标签),装有标题那个
        //div.content-tabs > div.page-tabs-content
        var marginLeftVal = WebUIJS_Frame.calSumWidth($(element).prevAll()), //前面所有tab的总宽度
            marginRightVal = WebUIJS_Frame.calSumWidth($(element).nextAll()); //后面所有tab的总宽度
        //一些按钮(向左,向右滑动)的总宽度
        var tabOuterWidth = WebUIJS_Frame.calSumWidth($(".content-tabs").children().not(".menuTabs"));
        // tab(a标签)显示区域的总宽度
        var visibleWidth = $(".content-tabs").outerWidth(true) - tabOuterWidth;
        //将要滚动的长度
        var scrollVal = 0;
        if ($(".page-tabs-content").outerWidth() < visibleWidth) {
            //所有的tab都可以显示的情况
            scrollVal = 0;
        } else if (marginRightVal <=
            (visibleWidth - $(element).outerWidth(true) - $(element).next().outerWidth(true))) {
            //向右滚动
            //marginRightVal(后面所有tab的总宽度)小于可视区域-(当前tab和下一个tab的宽度)
            if ((visibleWidth - $(element).next().outerWidth(true)) > marginRightVal) {
                scrollVal = marginLeftVal;
                var tabElement = element;
                while ((scrollVal - $(tabElement).outerWidth()) >
                    ($(".page-tabs-content").outerWidth() - visibleWidth)) {
                    scrollVal -= $(tabElement).prev().outerWidth();
                    tabElement = $(tabElement).prev();
                }
            }
        } else if (marginLeftVal > (visibleWidth - $(element).outerWidth(true) - $(element).prev().outerWidth(true))) {
            //向左滚动
            scrollVal = marginLeftVal - $(element).prev().outerWidth(true);
        }
        //执行动画
        $('.page-tabs-content').animate({
                marginLeft: 0 - scrollVal + 'px'
            },
            "fast");
    },

    editTabTitle: function(pageId, title) {
        var $title = WebUIJS_Frame.findTabTitle(pageId); //有tab的标题
        var $span = $title.children("span.page_tab_title");
        $span.text(title);
    },

    //计算多个jq对象的宽度和
    calSumWidth: function(element) {
        var width = 0;
        $(element).each(function() {
            width += $(this).outerWidth(true);
        });
        return width;
    },

    //关闭tab
    closeTab: function(item) {
        //item可以是a标签,也可以是i标签
        //它们都有data-id属性,获取完成之后就没事了
        var pageId = WebUIJS_Frame.getPageId(item);
        WebUIJS_Frame.closeTabByPageId(pageId);
    },

    closeTabByPageId: function(pageId) {
        var $title = WebUIJS_Frame.findTabTitle(pageId); //有tab的标题
        var $tabPanel = WebUIJS_Frame.findTabPanel(pageId); //装有iframe

        if ($title.hasClass("active")) {
            //要关闭的tab处于活动状态
            //要把active class传递给其它tab

            //优先传递给后面的tab,没有的话就传递给前一个
            var $nextTitle = $title.next();
            var activePageId;
            if ($nextTitle.length > 0) {
                activePageId = WebUIJS_Frame.getPageId($nextTitle);
            } else {
                activePageId = WebUIJS_Frame.getPageId($title.prev());
            }

            setTimeout(function() {
                    //某种bug，需要延迟执行
                    WebUIJS_Frame.activeTabByPageId(activePageId);
                },
                100);

        } else {
            //要关闭的tab不处于活动状态
            //直接移除就可以了,不用传active class

        }

        $title.remove();
        $tabPanel.remove();
        // scrollToTab($('.menu_tab.active')[0]);

    },

    closeOtherTabs : function (isAll) {
        if (isAll) {
            //关闭全部
            $('.page-tabs-content').children("[" + pageIdField + "]").find('.fa-remove').parents('a').each(function () {
                var $a = $(this);
                var pageId = WebUIJS_Frame.getPageId($a);
                WebUIJS_Frame.closeTabOnly(pageId);
    
                // closeTab($a);    
                /*$('#' + $(this).data('id')).remove();
                 $(this).remove();*/
            });
            var firstChild = $(".page-tabs-content").children().eq(0); //选中那些删不掉的第一个菜单
            if (firstChild) {
                //激活这个选项卡
                WebUIJS_Frame.activeTabByPageId(WebUIJS_Frame.getPageId(firstChild));
    
                /*$('#' + firstChild.data('id')).addClass('active');
                 firstChild.addClass('active');*/
            }
            else{
                setTitle(backuptitle);
            }
        } else {
            //除此之外全部删除
            $('.page-tabs-content').children("[" + pageIdField + "]").find('.fa-remove').parents('a').not(".active").each(function () {
                var $a = $(this);
                var pageId = WebUIJS_Frame.getPageId($a);
                WebUIJS_Frame.closeTabOnly(pageId);
    
                // closeTab($a);
                /*$('#' + $(this).data('id')).remove();
                 $(this).remove();*/
            });
    
        }
    },

    closeCurrentTab: function() {
        var pageId = WebUIJS_Frame.getActivePageId();
        if (WebUIJS_Frame.canRemoveTab(pageId)) {
            WebUIJS_Frame.closeTabByPageId(pageId);
        }
    },

    closeTabOnly:function(pageId) {
        var $title = WebUIJS_Frame.findTabTitle(pageId);//有tab的标题
        var $tabPanel = WebUIJS_Frame.findTabPanel(pageId);//装有iframe
        $title.remove();
        $tabPanel.remove();
    },
    

    refreshTabById: function(pageId) {
        var $iframe = WebUIJS_Frame.findIframeById(pageId);
        var url = $iframe.attr('src');

        if (url.indexOf(top.document.domain) < 0) {
            $iframe.attr("src", url); // 跨域状况下，重新设置url
        } else {
            $iframe[0].contentWindow.location.reload(true); //带参数刷新
        }

        WebUIJS.Loading();
    },

    refreshTab: function() {
        //刷新当前tab
        var pageId = WebUIJS_Frame.getActivePageId();
        WebUIJS_Frame.refreshTabById(pageId);
    },

    closeTab :function (item) {
        //item可以是a标签,也可以是i标签
        //它们都有data-id属性,获取完成之后就没事了
        var pageId = WebUIJS_Frame.getPageId(item);
        WebUIJS_Frame.closeTabByPageId(pageId);
    }
}

WebUIJS.AddIFrameTabs = function(options,onSuccessCallback) {
    var defaultTabOptions = {
        id: Math.random() * 200,
        urlType: "relative",
        title: "新页面",
        menukey:""
    };

    options = $.extend(true, defaultTabOptions, options);

    // if (options.urlType === "relative") {
    //     // var url = window.location.protocol + '//' + window.location.host + "/";
    //     var basePath = window.location.pathname + "/../";
    //     options.url = basePath + options.url;
    // }

    var pageId = options.id;

    //判断这个id的tab是否已经存在,不存在就新建一个
    if (WebUIJS_Frame.findTabPanel(pageId) === null) {

        //创建新TAB的title
        // title = '<a  id="tab_' + pageId + '"  data-id="' + pageId + '"  class="menu_tab" >';

        var $title = $('<a href="javascript:void(0);"></a>').attr(pageIdField, pageId).addClass("menu_tab");

        $title.data("menukey",options.menukey);

        var $text = $("<span class='page_tab_title'></span>").text(options.title).appendTo($title);
        // title += '<span class="page_tab_title">' + options.title + '</span>';

        //是否允许关闭
        if (options.close) {
            var $i = $("<i class='fa fa-remove page_tab_close' style='cursor: pointer' onclick='WebUIJS_Frame.closeTab(this);'></i>")
                .attr(pageIdField, pageId).appendTo($title);
            // title += ' <i class="fa fa-remove page_tab_close" style="cursor: pointer;" data-id="' + pageId + '" onclick="closeTab(this)"></i>';
        }

        //加入TABS
        $(".page-tabs-content").append($title);


        var $tabPanel = $('<div role="tabpanel" class="tab-pane"></div>').attr(pageIdField, pageId);

        if (options.content) {
            //是否指定TAB内容
            $tabPanel.append(options.content);
        } else {
            //没有内容，使用IFRAME打开链接

            //WebUIJS.Loading();

            var $iframe = $("<iframe></iframe>").attr("src", options.url).css("width", "100%").attr("frameborder", "no")
                .attr("id", "iframe_" + pageId).addClass("tab_iframe").attr(pageIdField, pageId);
            //frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="yes"  allowtransparency="yes"

            //iframe 加载完成事件

            $($iframe).on("load",
                function() {
                    //WebUIJS.CloseLoading();
                    WebUIJS_Frame.fixIframeCotent(); //修正高度
                    onSuccessCallback();
                });

            $tabPanel.append($iframe);

            WebUIJS_Frame.fixIframeCotent(); //修正高度
        }

        // $tab = $(content);
        $("#tab-content").append($tabPanel);

        $($title).click(function() {
            WebUIJS_Frame.activeTabByPageId(pageId);
        });

        //iframe 加载完成事件
        /*$tab.find("iframe").load(function () {
         App.fixIframeCotent();
         });*/
    }
    else{
        onSuccessCallback();
    }

    WebUIJS_Frame.activeTabByPageId(pageId);

};



function refreshMenu() {
    var mainMenu = $(".webui_mainmenu");

    var links = mainMenu.find("a[href]");

    links.each(function () {
      
        var href = $(this).attr("href");
        var menuKey=$(this).data("menukey");

        if (!href || startWith(href, "#") || startWith(href,"javascript:")) {
            return;
        }

        $(this).data("href", href);
        $(this).removeAttr("href");

        $(this).click(function (e) {
            var opts = {};

            if (!startWith(href, "http")) {
                opts.urlType = "relative";
            }

            opts.url = href;
            opts.close=true;
            opts.title=$(this).find("span").text();
            opts.menukey=menuKey;
            WebUIJS.Loading();

            WebUIJS.AddIFrameTabs(opts,function(){
                WebUIJS.CloseLoading();
            });

            e.stopPropagation();
            //e.cancelBubble();

            return false;
        });
    });

}


$(document).ready(function() {
    refreshMenu();

    $(window).resize(function(){
        WebUIJS_Frame.fixIframeCotent(); //修正高度
    })
});